# 通过查找轮廓的方式实现物体计数

import cv2

image_bgr = cv2.imread("images/rice.png")
if image_bgr is None:
    print("imread error\n")
    exit(1)

image_gray = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2GRAY)
cv2.imshow("image_gray", image_gray)
cv2.waitKey()

threshold_ret, image_binary = cv2.threshold(image_gray, 128.0, 255.0, cv2.THRESH_BINARY)
cv2.imshow("image_binary", image_binary)
cv2.waitKey()

# 返回轮廓集合，轮廓层级关系
contours, hierarchy = cv2.findContours(image_binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)

# 遍历轮廓
contour_index = 0 #轮廓索引
valid_contour_count = 0 #有效轮廓的数量
for contour in contours:
    # 计算每个轮廓的面积
    area_ret = cv2.contourArea(contour)
    if area_ret >= 10:
        valid_contour_count = valid_contour_count + 1

        # 绘制面积较大的轮廓
        cv2.drawContours(image_bgr, contours, contour_index, (0, 0, 255), 5)

        # 每个轮廓都是一个矩阵图像，若有需要，可以通过它的矩来求几何中心的坐标

    contour_index = contour_index + 1

text = "count=%ld" % valid_contour_count
cv2.putText(image_bgr, text, (0,50), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 0, 0), 2)
cv2.imshow("image_bgr", image_bgr)
cv2.waitKey()

cv2.destroyAllWindows()

exit(0)
